﻿using UnityEngine;
using Yoozoo.Gameplay.RTS;
using Yoozoo.Gta.Common;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

namespace Yoozoo.Gameplay.City
{
    [RequireComponent(typeof(ModelInstaning))]
    public class CityAiGangSetting : MonoBehaviour
    {
        private ModelInstaning _modelInstaning;
        
        private ResLoader _resLoader;
        private string _currentLogoPath;
        
        private void Start()
        {
            _modelInstaning = GetComponent<ModelInstaning>();
            UpdateGang();
            CityManager.OnUpdateGangSetting += UpdateGang;
        }

        private void UpdateGang()
        {
            string logoName = ResidentHandler.Inst.GetFunction("CityLuaFunction.getGangLogoName").Func<int,string>(0);
            string gangName = ResidentHandler.Inst.GetFunction("CityLuaFunction.getGangName").Func<int,string>(0);

            if (!string.IsNullOrEmpty(logoName))
            {
                _currentLogoPath = "Assets/ResourcesAssets/Texture/City/GangLogoLight/" + logoName + ".png";
                _resLoader = ResLoader.Alloc();
                _resLoader.Add2Load(_currentLogoPath, typeof(Texture2D), ((success, assetName, asset) =>
                {
                    if (!success)
                    {
                        return;
                    }

                    if (assetName != _currentLogoPath)
                    {
                        return;
                    }
                    
                    _modelInstaning.mat.SetTexture("_LogoTex",asset as Texture2D);
                }));
                _resLoader.Load();
            }
        }

        private void OnDestroy()
        {
            CityManager.OnUpdateGangSetting -= UpdateGang;
            if (_resLoader!=null)
            {
                _resLoader.Recycle2Cache();
                _resLoader = null;
            }
        }
    }
}